package com.cvr.project.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * 域名管理器
 * 用于管理应用的域名配置
 */
public class DomainManager {
    private static final String PREF_NAME = "domain_config";
    private static final String KEY_BASE_URL = "base_url";
    private static final String KEY_H5_URL = "h5_url";
    private static final String KEY_FIRST_LAUNCH = "first_launch";
    
    private static final String DEFAULT_BASE_URL = "https://prod.admin.hpxgyg.cn/api.php/";
    private static final String DEFAULT_H5_URL = "https://client.hpxgyg.cn/h5/#/pageB/terminal/index";
    
    private static DomainManager instance;
    private static Context appContext;
    private SharedPreferences sharedPreferences;
    
    private DomainManager() {
        sharedPreferences = appContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }
    
    /**
     * 初始化DomainManager，应该在Application中调用
     */
    public static synchronized void init(Context context) {
        if (appContext == null) {
            appContext = context.getApplicationContext();
            instance = new DomainManager();
        }
    }
    
    public static synchronized DomainManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException("DomainManager未初始化，请先在Application中调用init()方法");
        }
        return instance;
    }
    
    /**
     * 检查是否是首次启动
     */
    public boolean isFirstLaunch() {
        return sharedPreferences.getBoolean(KEY_FIRST_LAUNCH, true);
    }
    
    /**
     * 设置首次启动标记为false
     */
    public void setFirstLaunchCompleted() {
        sharedPreferences.edit().putBoolean(KEY_FIRST_LAUNCH, false).apply();
    }
    
    /**
     * 显示域名配置对话框
     */
    public void showDomainConfigDialog(Context context) {
        showDomainConfigDialog(context, null);
    }
    
    /**
     * 显示域名配置对话框
     */
    public void showDomainConfigDialog(Context context, OnDomainConfigListener listener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("域名配置");
        builder.setMessage("请输入服务器域名（不包含http://或https://）：");
        builder.setCancelable(false);
        
        final EditText apiEditText = new EditText(context);
        apiEditText.setHint("请输入接口域名：prod.admin.hpxgyg.cn");
        final EditText h5EditText = new EditText(context);
        h5EditText.setHint("请输入Web域名:client.hpxgyg.cn");
        final LinearLayout layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(apiEditText);
        layout.addView(h5EditText);
        builder.setView(layout);
        
        builder.setPositiveButton("确定", (dialog, which) -> {
            String apiDomain = apiEditText.getText().toString().trim();
            String h5Domain = h5EditText.getText().toString().trim();
            if (TextUtils.isEmpty(apiDomain)||TextUtils.isEmpty(h5Domain)) {
                Toast.makeText(context, "域名不能为空", Toast.LENGTH_SHORT).show();
                // 重新显示对话框
                showDomainConfigDialog(context, listener);
                return;
            }
            
            // 验证域名格式
            if (!isValidDomain(apiDomain)||!isValidDomain(h5Domain)) {
                Toast.makeText(context, "请输入有效的域名格式", Toast.LENGTH_SHORT).show();
                // 重新显示对话框
                showDomainConfigDialog(context, listener);
                return;
            }
            
            // 保存域名配置
            saveDomainConfig(apiDomain,h5Domain);
            setFirstLaunchCompleted();
            
            if (listener != null) {
                listener.onDomainConfigured(getBaseUrl(), getH5Url());
            }
        });
        
        builder.setNegativeButton("使用默认", (dialog, which) -> {
            // 使用默认域名
            saveDomainConfig("prod.admin.hpxgyg.cn", "client.hpxgyg.cn");
            setFirstLaunchCompleted();
            
            if (listener != null) {
                listener.onDomainConfigured(getBaseUrl(), getH5Url());
            }
        });
        
        builder.show();
    }
    
    /**
     * 验证域名格式
     */
    private boolean isValidDomain(String domain) {
        if (TextUtils.isEmpty(domain)) {
            return false;
        }
        
        // 移除可能的协议前缀
        domain = domain.replaceAll("^https?://", "");
        
        // 简单的域名格式验证
        String domainPattern = "^[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.[a-zA-Z]{2,}$";
        return domain.matches(domainPattern) || domain.matches("^[a-zA-Z0-9]([a-zA-Z0-9\\-\\.]{0,253}[a-zA-Z0-9])?$");
    }
    
    /**
     * 保存域名配置
     */
    private void saveDomainConfig(String apiDomain, String h5Domain) {
        // 确保域名不包含协议前缀
        apiDomain = apiDomain.replaceAll("^https?://", "");
        h5Domain = h5Domain.replaceAll("^https?://", "");

        String baseUrl = "https://" + apiDomain + "/api.php/";
        String h5Url = "https://" + h5Domain + "/h5/#/pageB/terminal/index";
        
        sharedPreferences.edit()
                .putString(KEY_BASE_URL, baseUrl)
                .putString(KEY_H5_URL, h5Url)
                .apply();
    }
    
    /**
     * 获取API基础URL
     */
    public String getBaseUrl() {
        return sharedPreferences.getString(KEY_BASE_URL, DEFAULT_BASE_URL);
    }
    
    /**
     * 获取H5页面URL
     */
    public String getH5Url() {
        return sharedPreferences.getString(KEY_H5_URL, DEFAULT_H5_URL);
    }
    
    /**
     * 静态方法获取API基础URL
     */
    public static String getStaticBaseUrl() {
        return getInstance().getBaseUrl();
    }
    
    /**
     * 静态方法获取H5页面URL
     */
    public static String getStaticH5Url() {
        return getInstance().getH5Url();
    }
    
    /**
     * 重置域名配置（用于测试或重新配置）
     */
    public void resetDomainConfig() {
        sharedPreferences.edit()
                .putBoolean(KEY_FIRST_LAUNCH, true)
                .remove(KEY_BASE_URL)
                .remove(KEY_H5_URL)
                .apply();
    }
    
    /**
     * 域名配置监听器
     */
    public interface OnDomainConfigListener {
        void onDomainConfigured(String baseUrl, String h5Url);
    }
}
